package _base0to1;

import _object.ListNode;

/**
 * 2. 两数相加
 */
public class No2 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode pre1 = null, cur1 = l1, nex1;
        while (cur1 != null) {
            nex1 = cur1.next;
            cur1.next = pre1;
            pre1 = cur1;
            cur1 = nex1;
        }
        ListNode pre2 = null, cur2 = l2, nex2;
        while (cur2 != null) {
            nex2 = cur2.next;
            cur2.next = pre2;
            pre2 = cur2;
            cur2 = nex2;
        }
        ListNode answer = new ListNode(-1, new ListNode(0));
        ListNode sent = answer;
        int sum = 0;
        while (true) {
            int pre1Val = 0, pre2Val = 0;
            if (pre1 != null) pre1Val = pre1.val;
            if (pre2 != null) pre2Val = pre2.val;
            sum = pre1Val + pre2Val + sum / 10;
            if (pre1 == null && pre2 == null && sum == 0) break;
            answer.next = new ListNode(sum % 10);
            answer = answer.next;
            if (pre1 != null) pre1 = pre1.next;
            if (pre2 != null) pre2 = pre2.next;
        }
        ListNode pre = null, cur = sent.next, nex;
        while (cur != null) {
            nex = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nex;
        }
        return pre;
    }
}
